/**
* Copyright @ 2023 iAuto (Shanghai) Co., Ltd.
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are NOT permitted except as agreed by
* iAuto (Shanghai) Co., Ltd.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/

import React, { useCallback, useEffect, useState } from 'react';

// 非官方库
import { connect } from 'dva';
import {
  Button,
  Col,
  Form,
  Input,
  message,
  Row,
  Select,
  Upload,
  Modal,
  ConfigProvider,
  Table,
  TableColumnsType,
  Tooltip,
  Card,
  Dropdown,
  Space,
  Menu,
  Divider,
} from 'antd';
import {
  // ExclamationCircleOutlined,
  SearchOutlined,
  UpOutlined,
  DownOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';

// 业务组件
import CarModelTreeSelect from '@/components/CarModelTreeSelect';
import PageTabs from '@/components/common/PageTabs';
import DrawerAbilityDetail from './DrawerAbilityDetail';
import { anyObj } from '@/types/components';
import ModalWin from '@/components/common/ModalWin';
import CustomSpin from '@/components/common/CustomSpin';
import useAuth from '@/utils/soa/useAuth';


// 请求
import {
  getAbilityList,
  getStatusList,
  publishAbility,
  getAbilityVersionList,
  abilitySocDel,
  backAbility,
  exportExcel,
  importExcelCheck,
  offShelf,
  getPublishList,
} from '@/services/ability';
import { getSocList } from '@/services/soc';

// 静态资源
import styles from './index.less';

import { RcFile, UploadProps } from 'antd/es/upload/interface';
import { TablePaginationConfig } from 'antd/es/table';
import {
  FormValues,
  CartypeResultItem,
  abilityItem,
  ModalType,
  ExpandedDataType,
} from '@/types/ability';

import {
  emptyText,
  showTotal,
  renderIcon,
  renderModalTitle,
  downloadFile,
  renderRowClassName,
} from './utils';
import { downloadAbilityFile } from '@/services/downloadURLFile';
import CarModel, { TextTitle } from '../serviceManage/servicePublishing/CarModel';
import { useMount, useRequest, useUnmount } from 'ahooks';
import { getSeriesModelList } from '@/services/soa/sceneOfficial';
import { TaskModel } from '@/models/soaTask';
import { checkUploadStatus, getLocalStorage, initLocalStorage, setLocalStorage } from '@/utils/block';
import RequestSequence from './components/RequestSequence';

const { Option } = Select;
const { TextArea } = Input;
const RES_SUCCESS = '0';
const tabPaneList = ['状态记录', '未发布能力', '已发布能力'];

const ConfirmActionType = {
  cleanup: 'cleanup',
  takedown: 'takedown',
  publish: 'publish',
  export: 'export',
  import: 'import',
  importExcel: 'importExcel'
};

const Index: React.FC<any> = ({ dispatch, menu }) => {
  // 是否正在请求
  const [isRequest, setIsRequest] = React.useState(false)
  // 品牌
  const [brandName, setBrandName] = React.useState<any>(localStorage.getItem('tenantCode'));
  // 激活的tab
  const [activeKey, setActiveKey] = useState<number | string>(1);
  // 是否显示导入弹窗
  const [isModalVisible, setIsModalVisible] = useState(false);
  // 导入弹窗确认按钮是否loading
  const [importBtnLoading, setImportBtnLoading] = useState(false);
  // 导出弹窗确认按钮是否loading
  const [exportFileLoading, seteExportFileLoading] = useState(false);
  // 退回原因弹窗
  const [isModalBack, setIsModalBack] = useState(false);
  // 未发布能力数量
  const [unpublishTotal, setUnpublishTotal] = useState(0);
  //  能力名称
  const [skillName, setSkillName] = useState<string>('');
  // 车型车系
  const [cartype, setCartype] = useState<CartypeResultItem[]>([]);
  // 车型车系Map
  const [carMap, setCarMap] = useState({});
  // 车系默认值数组
  const [cartypeVal, setCartypeVal] = useState<any>([]);
  // 服务矩阵版本号列表
  const [socVersions, setSocVersions] = useState<string[]>([]);
  // 服务矩阵版本号
  const [socVersion, setSocVersion] = useState('');
  // 是否是状态记录查看
  const [statusDetail, setStatusDetail] = useState(false);
  const [seriesName, setSeriesName] = useState('');
  const [modelName, setModelName] = useState('');
  const [loading, setLoading] = useState(true);
  const [showDetail, setShowDetail] = useState(false);
  const [detailInfo, setDetailInfo] = useState<any>({ id: null });
  // 能力列表
  const [abilityList, setAbilityList] = useState<abilityItem[]>([]);
  // 是否发布 （0：未发布 1：已发布）
  const [status, setStatus] = useState<any>(-1);
  // 导入弹窗中soc版本号
  const [importCarModeVersion, setImportCarModeVersion] = useState<any>('');
  // 导入弹窗中车soc列表
  // 文件
  const [fileList, setFileList] = useState<any>([]);
  // 是否发布成功
  const [isPublish, setIsPublish] = useState(false);
  // 是否已退回
  const [isBack, setIsBack] = useState(false);
  // 弹窗对象
  const [currentModal, setCurrentModal] = useState<ModalType | null>(null);
  // 车系默认值拷贝
  const [carModalCopy, setcarModalCopy] = useState<string[]>([]);
  const [pagination, setPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  // form对象
  const [form] = Form.useForm();
  const [modelOptions, setModelOptions] = useState<{ title?: React.ReactNode; content?: React.ReactNode; handleOk?: () => void }>({});
  // 按钮权限map
  const hasAuth = {
    'import': useAuth('/soaManage/abilitymanagement/abilitymanagement_doImport', menu),
    'unpublishexport': useAuth('/soaManage/abilitymanagement/abilitymanagement_doUnPublishExport', menu),
    'publishexport': useAuth('/soaManage/abilitymanagement/abilitymanagement_doPublishExport', menu),
    'back': useAuth('/soaManage/abilitymanagement/abilitymanagement_doBack', menu),
    'publish': useAuth('/soaManage/abilitymanagement/abilitymanagement_doPublish', menu),
    'cleanUp': useAuth('/soaManage/abilitymanagement/abilitymanagement_doCleanUp', menu),
    'takeDown': useAuth('/soaManage/abilitymanagement/abilitymanagement_doTakeDown', menu),
  }

  const [carSeries, setCarSeries] = useState([])
  const [carModels, setCarModels] = useState([])
  const [publishList, setPublishList] = useState<any[]>([])
  const [carModelList, setCarModelList] = useState<any[]>([])
  const seriesModelList = useRequest(getSeriesModelList);

  const propsForUpload: UploadProps = {
    showUploadList: false,
    onRemove: (file) => {
      const index = fileList.indexOf(file);
      const newFileList = fileList.slice();
      newFileList.splice(index, 1);
      setFileList(newFileList);
    },
    beforeUpload: (file) => {
      setFileList([file]);
      return false;
    },
    fileList,
  };

  useUnmount(() => {
    initLocalStorage()
  })

  useMount(() => {
    initLocalStorage()
  })

  // 切换tab
  const handleTabChange = (e: any) => {
    setActiveKey(e);
    setSkillName('');
    setAbilityList([]);
    if (e == 1) {
      setStatus(-1);
    }
    if ([2, 3].includes(e)) {
      setCartypeVal([]);
      setStatus(Number(e) - 2);
      setSocVersions([]);
      setSocVersion('');
    }
    setLoading(true);
    setPagination((state) => {
      return {
        ...state,
        total: 0,
        current: 1,
        pageSize: 10,
      };
    });
  };

  // 选择车系车型
  const emitSelect = (e: any) => {
    // 清空soc版本号
    setSocVersion('');
    const [seriesCode, modelCode] = e;
    if (!(seriesCode && modelCode)) {
      return
    }
    setCartypeVal(e);

    // 切换 车型车系的时候设置一下
    setSeriesName(carMap[seriesCode]?.seriesName);
    setModelName(carMap[seriesCode]?.models[modelCode]?.modelName);

    if (status === 0) {
      if (carMap[seriesCode] && carMap[seriesCode].models && carMap[seriesCode].models[modelCode]) {
        const compact = (item: any[]) => item.filter(Boolean);
        const socVersions = compact([carMap[seriesCode].models[modelCode].socVersion])|| []
        const socVersion = compact([carMap[seriesCode].models[modelCode].socVersion])?.[0]
        if (socVersion) {
          setSocVersions(socVersions);
          setSocVersion(socVersion);
          getList(1, pagination.pageSize, e, socVersion, 0);
        } else {
          setSocVersions([]);
          setSocVersion('');
          setAbilityList([]);
          setPagination((state) => {
            return {
              ...state,
              total: 0,
              current: 1,
              pageSize: 10,
            };
          });
        }
      } else {
        setSocVersion('');
      }
    } else {
      const params = {
        modelCode,
        seriesCode,
        status,
        current: 1,
        pagesize: 1000,
      };
      if (dispatch) {
        setLoading(true);
        getAbilityVersionList(params).then((res: any) => {
          setLoading(false);
          const versions: string[] = [];
          res.data.dataList.forEach((item: any) => {
            item.socVersion.forEach((versionItem: any) => {
              if (!versions.includes(versionItem.socVersion)) {
                versions.push(versionItem.socVersion);
              }
            });
          });
          setSocVersions(versions);
          setSocVersion(versions?.[0]);
          if (status == 1) {
            getList(1, pagination.pageSize, e, versions[0], 1);
          }
        });
      }
    }
  };

  // 获取能力列表
  const getList = async (
    pn = 1,
    pageSize = pagination.pageSize,
    dataCar = cartypeVal,
    dataSoc = socVersion,
    status = 0,
  ) => {
    if (!dataCar.length) {
      setLoading(false);
      return;
    }
    // 如果没有选中socVersion不查询
    if (!dataSoc) {
      // 如果只有一个未发布的版本，清空以后此时无未发布的版本，需要把列表数据清空
      setAbilityList([]);
      setLoading(false);
      return;
    }
    const data = {
      skillName,
      status,
      socVersion: dataSoc,
      current: pn,
      pagesize: pageSize,
      modelCode: dataCar[1],
      seriesCode: dataCar[0],
    };
    setLoading(true);
    const res = await getAbilityList(data);
    if (res?.statusCode == RES_SUCCESS) {
      setLoading(false);
      if (Array.isArray(res?.data.dataList)) {
        setIsBack(res?.data.dataList.every((item) => item.status == '2'));
        setAbilityList(res?.data.dataList || []);
      }
    }
    setPagination((state) => {
      return {
        ...state,
        total: res?.data?.pageCount || 0,
        current: data.current,
        pageSize: res?.data?.pageSize || pageSize,
      };
    });
  };

  // 获取状态记录列表
  const getStatusLists = useCallback(async (pn = 1, pageSize = 10) => {
    const data = {
      pagesize: pageSize,
      current: pn,
    };
    setLoading(true);
    const res = await getStatusList(data);
    if (res?.statusCode == RES_SUCCESS) {
      setLoading(false);
      if (Array.isArray(res?.data.dataList)) {
        setAbilityList(res?.data.dataList || []);
      }
      setPagination((state) => {
        return {
          ...state,
          total: res?.data?.pageCount || 0,
          current: data.current,
          pageSize: res?.data?.pageSize || pageSize,
        };
      });
    }
  }, []);

  const handleCarModelMap = (res: any) => {
    // 从响应数据中提取allCarModelMap，如果不存在则默认为空对象
    const allCarModelMap = res?.data?.allCarModelMap || {};
    const keysName = Object.keys(allCarModelMap);
    let defaultItem = ['', '', ''];
  
    // 根据特定条件找到默认项
    for (const key of keysName) {
      const keyItem = allCarModelMap[key];
      console.log("🚀 ~ file: index.tsx ~ line 371 ~ handleCarModelMap ~ keyItem", keyItem)
      if (keyItem.labelNum) {
        const childItem = keyItem.children;
        for (const item of childItem) {
          if (item.showDot) {
            defaultItem = [keyItem.value || '', item.value || '', item.socVersion || ''];
            break;
          } 
        }
        break;
      } else if (!defaultItem[1] && keyItem.children && keyItem.children.length) {
        const target = keyItem.children.find((child: any) => child.socVersion === null)
        defaultItem = [
          keyItem.value || '',
          target?.value || '',
          target?.socVersion || '',
        ];
      }
    }
  
    return defaultItem;
  };
  
  const handleUnpublishedData = (defaultItem: string[], res: any) => {
    const allCarModelMap = res?.data?.allCarModelMap || {};

    if (!statusDetail) {
      console.log(defaultItem, 'defaultItem');
      setcarModalCopy(defaultItem);
    } else {
      console.log(cartypeVal, 'cartypeVal');
      setcarModalCopy(cartypeVal);
    }
    // 根据状态和是否存在未发布数据处理不同情况
    if (status === 0) {
      if (!statusDetail) {
        const [seriesCode = '', modelCode = ''] = [defaultItem[0], defaultItem[1]];
        if (!(seriesCode && modelCode)) {
          // 如果seriesCode和modelCode不存在，则返回
          return;
        }
  
        // 检查所选seriesCode和modelCode是否存在models
        if (
          allCarModelMap[seriesCode]?.models &&
          allCarModelMap[seriesCode].models[modelCode]
        ) {
          const socVal = allCarModelMap[seriesCode]?.models[modelCode]?.socVersion;
          if (res.data.unpublishTotal) {
            setSocVersion(socVal || '');
            setCartypeVal([defaultItem[0], defaultItem[1]]);
            getList(1, pagination.pageSize, [defaultItem[0], defaultItem[1]], socVal, 0);
          }
        }
      } else {
        getList(1, pagination.pageSize, cartypeVal, socVersion, 1);
        setStatusDetail(false);
      }
    } else if (status === 1) {
      setSocVersion(socVersion);
      if (!statusDetail) {
        if (isPublish) {
          setCartypeVal(cartypeVal);
          setSocVersion(socVersion);
          setIsPublish(false);
          getList(1, pagination.pageSize, cartypeVal, socVersion, 1);
        } else {
          setTimeout(() => {
            emitSelect(carModalCopy.slice(0, 2));
          });
        }
      } else {
        getList(1, pagination.pageSize, cartypeVal, socVersion, 1);
        setStatusDetail(false);
      }
    }
  };
  
  const getCarType = async (cb:any = null) => {
    setLoading(true);
    if (dispatch) {
      dispatch({
        type: 'abilityModel/getAbilityPublishDetail',
      }).then((res: any) => {
        setLoading(false);
        cb?.();
        // 处理allCarModelMap并找到默认项
        const defaultItem = handleCarModelMap(res);
  
        // 处理不同状态下的未发布数据
        handleUnpublishedData(defaultItem, res);
  
        // 根据状态和未发布数据更新状态
        if (!statusDetail) {
          // 根据carMap和defaultItem更新状态
          if (res?.data?.allCarModelMap && defaultItem.length > 0) {
            if (res.data.allCarModelMap[defaultItem[0]]) {
              setSeriesName(res.data.allCarModelMap[defaultItem[0]].seriesName);
            }
            if (res.data.allCarModelMap[defaultItem[0]]?.models) {
              setModelName(res.data.allCarModelMap[defaultItem[0]]?.models[defaultItem[1]]?.modelName);
            }
          }
          setCarMap(res?.data?.allCarModelMap || {});
          setCartype(res?.data?.allCarModelList?.length ? res?.data?.allCarModelList : []);
          setUnpublishTotal(res.data.unpublishTotal || 0);
        } else {
          // 根据carMap和cartypeVal更新状态
          if (res?.data?.allCarModelMap && cartypeVal.length > 0) {
            if (res.data.allCarModelMap[cartypeVal[0]]) {
              setSeriesName(res.data.allCarModelMap[cartypeVal[0]].seriesName);
            }
            if (res.data.allCarModelMap[cartypeVal[0]]?.models) {
              setModelName(res.data.allCarModelMap[cartypeVal[0]]?.models[cartypeVal[1]]?.modelName);
            }
          }
        }
      });
    }
  };

  const afterCheckimportExcel = ({ carSeries = [], carModels = [] }) => {
    setImportBtnLoading(true);
    const formData = new FormData();
    fileList.forEach((file: any) => {
      formData.append('file', file as RcFile);
    });
    formData.append('seriesCode', carSeries[0]);
    formData.append('modelCode', carModels.join(','));
    formData.append('socVersion', importCarModeVersion);
    setLoading(true);
    if (dispatch) {
      dispatch({
        type: 'abilityModel/getabilityImport',
        payload: formData,
      }).then(
        (res: any) => {
          setLoading(false);
          setIsModalVisible(false);
          setImportBtnLoading(false);
          if (res?.statusCode === RES_SUCCESS) {
            // message.success('导入完成！');
            setLocalStorage('uploadStatus', 'completed')
            // getCarType();
          } else if (res?.statusCode == '40070305') {
            showConfirm({
              actionType: 'import',
              content: '能力重复，请检查',
              okText: '确认',
              // cancelCallback: resetUnpublishData,
              okCallback() {
                setLocalStorage('uploadStatus', 'failed')
              },
            });
          } else if (res?.statusCode == '40070415') {
            // message.error('文件格式错误，请检查文件');
            showConfirm({
              actionType: 'import',
              content: '能力数据格式错误，请检查文件',
              okText: '确认',
              okCallback() {
                setLocalStorage('uploadStatus', 'failed')
              },
            });
          } else if (res?.statusCode === '40070901') {
            const errorText = res?.data?.errorList?.map(
              (item: any, index: number) =>
                <div key={index}>{`SkillId：${item?.skillId} ServiceId：${item.serviceId} FunctionId：${item.functionId}`}</div>
            )
            const errorContent = <div>
              <p>当前soc版本 服务管理数据与能力数据对应错误</p>
              <p style={{ maxHeight: 300, overflow: 'auto', marginTop: 20 }}>{errorText}</p>
            </div>
            showConfirm({
              actionType: 'import',
              content: errorContent,
              okCallback() {
                setLocalStorage('uploadStatus', 'failed')
              },
            });
          } else if (res?.statusCode == '40070902') {
            const errorText = res?.data?.errorList?.map(
              (item: any, index: number) =>
                <div key={index}>{`SkillId：${item?.skillId} ServiceId：${item.serviceId} FunctionId：${item.functionId}`}</div>
            )
            const errorContent = <div>
              <p>{res?.statusMessage || 'judgement错误'}</p>
              <p style={{ maxHeight: 300, overflow: 'auto', marginTop: 20 }}>{errorText}</p>
            </div>
            showConfirm({
              actionType: 'import',
              content: errorContent,
              okText: '确认',
              okCallback() {
                setLocalStorage('uploadStatus', 'failed')
              },
            });
          } else {
            //! 只要是 else 都要走这个逻辑 
            const errorText = res?.data?.errorList?.map(
              (item: any, index: number) =>
                <div key={index}>{item && JSON.stringify(item)}</div>
            )
            const errorContent = <div>
              <p>{res?.statusMessage || '服务器发生错误，请检查服务器。'}</p>
              <p style={{ maxHeight: 300, overflow: 'auto', marginTop: 20 }}>{errorText}</p>
            </div>
            showConfirm({
              actionType: 'import',
              content: errorContent,
              okText: '确认',
              okCallback() {
                setLocalStorage('uploadStatus', 'failed')
              },
            });
            // 理解不了的 statusCode 也走清理函数
            // resetUnpublishData();
          }
          // 去除多余业务提示
          //  else {
          //   message.error(res?.statusMessage);
          // }
        },
        () => {
          setIsModalVisible(false);
          setImportBtnLoading(false);
        },
      );
    }
  };

  // 清理未发布数据
  const resetUnpublishData = () => {
    setCartypeVal([]);
    setImportCarModeVersion('');
    setSocVersion("");
    setUnpublishTotal(0);
    setAbilityList([]);
    setFileList([]);
    setPagination((state) => {
      return {
        ...state,
        total: 0,
        current: 1,
        pageSize: 10,
      };
    });
  }

  type ActionType = 'cleanup' | 'takedown' | 'publish' | 'export' | 'import' | 'importExcel';

  interface ShowConfirmOption {
    actionType: ActionType;
    content: string | undefined | React.ReactNode;
    okText?: string;
    cancelText?: string;
    cancelCallback?: () => void;
    okCallback?: () => void;
    paramObj?: object;
    closable?: boolean;
  }

  const showConfirm = useCallback(
    (confirmOption: ShowConfirmOption) => {
      Modal.confirm({
        width: 600,
        keyboard: false,
        wrapClassName: styles.confirmModal,
        icon: null,
        content: confirmOption.content,
        okText: confirmOption.okText || '确定',
        cancelText: confirmOption.cancelText || '取消',
        okButtonProps: {
          size: 'small',
        },
        cancelButtonProps: {
          size: 'small',
          style: {
            display: confirmOption?.cancelCallback ? 'inline-block' : 'none'
          }
        },
        closable: confirmOption.closable ?? false,
        onOk() {
          switch (confirmOption.actionType) {
            case ConfirmActionType.cleanup: {
              setLoading(true);
              const params = { socVersion, modelCode: cartypeVal[1], seriesCode: cartypeVal[0] };
              abilitySocDel(params).then((res) => {
                if (res?.statusCode == RES_SUCCESS) {
                  // message.success('清空完成');
                  // 修复清空文案提示
                  message.success(`车型:${carMap[cartypeVal[0]]?.seriesName || ''}/${carMap[cartypeVal[0]]?.models[cartypeVal[1]]?.modelName} 已清空`);
                  getCarType(resetUnpublishData);
                }
                // else {
                //   message.error(res?.statusMessage);
                // }
              });
              break;
            }
            case ConfirmActionType.takedown: {
              setLoading(true);
              const [seriesCode, modelCode] = cartypeVal;
              const params = { seriesCode, modelCode, socVersion };
              offShelf(params).then((res) => {
                setLoading(false);
                if (res?.statusCode == RES_SUCCESS) {
                  message.success('下架成功');
                  // 清空列表数据，soc版本号列表,切换到未发布页面
                  setActiveKey(2);
                  setStatus(0);
                  setAbilityList([]);
                  setSocVersions([]);
                }
                // else {
                //   message.error(res?.statusMessage);
                // }
              });
              break;
            }
            case ConfirmActionType.publish: {
              handlePublishOk();
              break;
            }
            case ConfirmActionType.export: {
              exportFileOk();
              break;
            }
            case ConfirmActionType.importExcel: {
              afterCheckimportExcel(confirmOption.paramObj || {});
              break;
            }
          }
          confirmOption?.okCallback?.()
        },
        onCancel() {
          setLocalStorage('uploadStatus', 'failed')
          confirmOption?.cancelCallback?.()
        }
      });
    },
    [cartypeVal, socVersion, isPublish, statusDetail, fileList],
  );

  const renderAction = (actionType: string) => {
    if (actionType === 'publish') {
      return;
    } else if (actionType === 'export') {
      return exportFileOk();
    } else {
      return null;
    }
  };

  const handleModalCancel = useCallback(
    (currentModal: any) => {
      setCurrentModal({ actionType: currentModal.actionType, visible: false });
    },
    [currentModal],
  );

  // 取消导入
  const handleImportCancel = () => {
    setIsModalVisible(false)
    setImportCarModeVersion('')
  }
  // 导入
  const handleImportOk = async (
    { carSeries = [], carModels = [] },
    isAuto = false,
  ) => {
    if (isRequest) {
      return
    }
    if (!carSeries?.length) {
      // 没有选择车系
      message.warning('请选择车系!');
      return
    }
    if (!carModels?.length) {
        // 没有选择车型
        message.warning('请选择车型!');
        return
    }
    if (!importCarModeVersion) {
      message.error('请选择服务矩阵版本号');
      return;
    }
    if (!fileList.length) {
      message.error('请上传excel');
      return;
    }

    if (!isAuto) {
      // 生成请求列表
      const tasks: TaskModel['state']['tasks'] = [];
      const reqList = carModels.map((val, index) => {
          tasks.push({
              id: (index + 1).toString(),
              brandCode: brandName as string,
              brandName: brandName as string,
              seriesCode: carSeries[0],
              seriesName: carMap[carSeries[0]]?.seriesName,
              modelCode: val,
              modelName: carMap[carSeries[0]]?.models[val]?.modelName,
              version: importCarModeVersion || '',
              status: 1
          })
          return {
            carSeries: carSeries,
            carModels: [val],
            id: (index + 1).toString(),
          }
      })
      // 添加任务列表
      dispatch({
          type: 'task/addTasks',
          payload: tasks
      })
  
      // 开始任务
      let index = 0;
      for (const req of reqList) {
          setLocalStorage('uploadStatus', 'pending')
          dispatch({
              type: 'task/updateTaskStatus',
              payload: {
                  taskId: req.id,
                  newStatus: 2, //导入中
                  disabled: true
              }
          })
          // 自动任务
          handleImportOk(req, true)
          
          // 查询执行状态结果
          const upStatus = await checkUploadStatus()
  
          if (upStatus === 'completed') { // 成功
              dispatch({
                  type: 'task/updateTaskStatus',
                  payload: {
                      taskId: req.id,
                      newStatus: 3, //导入中
                      disabled: index === reqList.length ? false : true
                  }
              })
          } else if(upStatus === 'failed') { // 失败
              break;
          }
          index ++
      }
      // 结算状态
      dispatch({
          type: 'task/updateAllTaskStatus'
      })

      // todo 后续

      getCarType(resetUnpublishData);
      setIsRequest(false);
      return
    }


    setLoading(true);
    setIsModalVisible(false);
    setIsRequest(true)
    const formData = new FormData();
    fileList.forEach((file: any) => {
      formData.append('file', file as RcFile);
    });
    formData.append('seriesCode', carSeries[0]);
    formData.append('modelCode', carModels.join(','));
    // formData.append('modelName', modelName);
    // formData.append('seriesName', seriesName);
    formData.append('socVersion', importCarModeVersion);
    const res = await importExcelCheck(formData);
    setLoading(false);
    const code = res?.statusCode;
    if (code == RES_SUCCESS) {
      afterCheckimportExcel({ carSeries, carModels });
    } else if (code == '40079527') {
      // 需要业务提示
      // showConfirm('import', '继续导入已经有未发布能力将被覆盖。是否继续？', code);
      // Modal.confirm({
      //   width: 700,
      //   title: '提示',
      //   keyboard: false,
      //   icon: <ExclamationCircleOutlined />,
      //   content: '继续导入已经有未发布能力将被覆盖。是否继续？',
      //   okText: '确认',
      //   cancelText: '取消',
      //   onOk() {
      //     afterCheckimportExcel();
      //   },
      // });
      if (getLocalStorage('isConfirm', false)) {
        afterCheckimportExcel({ carSeries, carModels });
        return
      }
      showConfirm({
        actionType: 'importExcel',
        content: '继续导入已经有未发布能力将被覆盖。是否继续？',
        okText: '确认',
        paramObj: { carSeries, carModels },
        cancelCallback() {
          //
        },
        okCallback() {
          setLocalStorage('isConfirm', true)
        },
      });
    } else if (code == '40070305') {
      showConfirm({
        actionType: 'import',
        content: '能力重复，请检查',
        okText: '确认',
        okCallback() {
          setLocalStorage('uploadStatus', 'failed')
        },
      });
    }
    else if (code == '40070409') {
      showConfirm({
        actionType: 'import',
        content: '当前正在导入，请稍后再试！',
        okText: '确认',
        okCallback() {
          setLocalStorage('uploadStatus', 'failed')
        },
      });
    }
    else if (code == '40070415') {
      showConfirm({
        actionType: 'import',
        content: '能力数据格式错误，请检查文件',
        okText: '确认',
        okCallback() {
          setLocalStorage('uploadStatus', 'failed')
        },
      });
    }
    setIsRequest(false);
  };

  // 导出 未发布&已发布
  const exportFileOk = async () => {
    seteExportFileLoading(true);
    const params = { socVersion, modelCode: cartypeVal[1], seriesCode: cartypeVal[0] };
    setLoading(true);
    exportExcel(params).then((res: any) => {
      setLoading(false);
      seteExportFileLoading(false);
      if (res?.statusCode == RES_SUCCESS) {
        const URL = res?.data?.fileAddr;
        const seriesName = carMap[cartypeVal[0]]?.seriesName || '导出';
        const modelName = carMap[cartypeVal[0]]?.models[cartypeVal[1]]?.modelName || '文件';
        downloadFile(URL, `${seriesName}/${modelName} 车型${socVersion || ''}能力.xlsx`);
      }
      // else {
      //   message.error(res?.statusMessage);
      // }
    });
  };

  // 清空
  const handleCleanUp = () => {
    // const sn = carMap[cartypeVal[0]]?.seriesName || '';
    // const mn = carMap[cartypeVal[0]]?.models[cartypeVal[1]]?.modelName || '';
    // showConfirm({
    //   actionType: 'cleanup',
    //   content: (
    //     <Row>
    //       即将清空{sn}车系/{mn}车型{socVersion}版本的未发布能力,是否确定清空？
    //     </Row>
    //   ),
    // });
    setIsModalBack(true);
    setModelOptions({
      title: <TextTitle text='清空' />,
      content: <CarModel form={form} seriesModelList={seriesModelList} />,
      handleOk: async () => {
        form
        .validateFields()
        .then((values) => {
          if (!values.carSeries?.length) {
            // 没有选择车系
            message.warning('请选择车系!');
            return
          }
          if (!values.carModels?.length) {
            // 没有选择车型
            message.warning('请选择车型!');
            return
          }
          setLoading(true);
          const data = {
            seriesCode: values.carSeries[0],
            modelCode: values.carModels.join(','),
            // socVersion: '',
          };
          handleCancel();
          abilitySocDel(data).then((res) => {
            setLoading(false);
            // setIsModalBack(false);
            if (res?.statusCode == RES_SUCCESS) {
              // message.success('清空完成');
              // 修复清空文案提示
              message.success(`已清空`);
              getCarType(resetUnpublishData);
            } else {
              message.warning('能力清空失败');
            }
          });
        })
      }
    })
  };

  // 退回-确定
  const handleBackOk = () => {
    form
      .validateFields()
      .then((values) => {
        if (!values.carSeries?.length) {
          // 没有选择车系
          message.warning('请选择车系!');
          return
        }
        if (!values.carModels?.length) {
            // 没有选择车型
            message.warning('请选择车型!');
            return
        }
        if (!values.reason) {
            // 没有选择车型
            message.warning('请填写原因!');
            return
        }
        const data = {
            seriesCode: values.carSeries[0],
            modelCode: values.carModels.join(','),
            socVersion: '',
            reason: values.reason,
        };
        
        setLoading(true);
        backAbility(data).then((res) => {
          setLoading(false);
          if (res?.statusCode == RES_SUCCESS) {
            message.success('退回成功');
            getCarType();
          }
          // else {
          //   message.error(res?.statusMessage);
          // }
        });
        handleCancel();
      })
      .catch((err) => console.log(err));
  };

  // 下架
  const handleTakeDown = () => {
    // 产品和后端确认后，去除查询可下架版本逻辑，改为下架当前查询的soc版本
    showConfirm({
      actionType: 'takedown',
      content: (
        <Row>
          <Col span={24}>
            {socVersion}版本的能力将要下架，能力可能被场景使用中，下架能力可能造成严重问题，确定要下架吗？
          </Col>
        </Row>
      ),
      closable: true,
      okText: '确认',
      cancelText: '取消',
      cancelCallback() {
        //
      },
    });
  };

  // 获取变更列表
  const getChangeList = useCallback(() => {
    setIsModalBack(true);
    setModelOptions({
      title: <TextTitle text='发布' />,
      content: <CarModel form={form} seriesModelList={seriesModelList} />,
      handleOk: handlePublishOk
    })
  }, [form, seriesModelList]);

  // 获取已发布的soc版本号列表
  const getPublishedSocList = (shouldSet = true, seriesCode: string, modelCode: string) => {
    const payLoad = {
      modelCode,
      seriesCode,
      status: 1,
      current: 1,
      pagesize: 1000,
    };
    setLoading(true);
    getAbilityVersionList(payLoad).then((res: any) => {
      setLoading(false);
      const versions: string[] = [];
      res.data.dataList.forEach((item: any) => {
        item.socVersion.forEach((versionItem: any) => {
          if (!versions.includes(versionItem.socVersion)) {
            versions.push(versionItem.socVersion);
          }
        });
      });
      setSocVersions(versions);
      // 是否要默认选中列表中的第一个
      if (shouldSet) {
        setSocVersion(versions?.[0]);
      }
    });
  }

  const handleProvinceChange = async (value: string) => {
    setCarSeries([value]);
    // 调用接口
    const res = await getPublishList({ sCode: value });
    if (res.statusCode === '0') {
      setPublishList(res?.data || []);
    }
  }

  const handleCarModelOnchange = async (value: string[]) => {
    setCarModels(value);
  }

  const allSelected = () => {
    setCarModels(carModelList.map((item: any) => item.code));
  };

  const clearAll = () => {
    setCarModels([])
  };

  const handleSocVersionChange = (value: string, option: any) => {
    setCarModels([]);
    setImportCarModeVersion(value);
    const target = publishList[option.key];
    for (const obj of seriesModelList?.data?.data || []) {
      if (carSeries[0] === obj?.code) {
        // 组合一些 CarModels name
        setCarModelList(obj?.children.filter((item: any) => target?.modelCodes.includes(item.code)) || []);
      }
    }
  }

  // 发布-确定
  const handlePublishOk = async () => {
    form
      .validateFields()
      .then(async (values) => {
        if (!values.carSeries?.length) {
          // 没有选择车系
          message.warning('请选择车系!');
          return
        }
        if (!values.carModels?.length) {
            // 没有选择车型
            message.warning('请选择车型!');
            return
        }
        const data = {
            seriesCode: values.carSeries[0],
            modelCode: values.carModels.join(','),
            // socVersion: '',
        };
        setLoading(true);
        const res = await publishAbility(data);
        setLoading(false);
        if (res?.statusCode == RES_SUCCESS) {
          message.success('发布成功');
          setIsPublish(true);
          setStatus(1);
          setActiveKey(3);
          getPublishedSocList(true, values.carSeries[0], values.carModels[0]);
          // 修复发布成功切换到未发布能力未清空soc版本号问题
          setImportCarModeVersion('');
        } else {
          message.error('能力发布失败!'); // 需要业务提示-xxx重复,不可重复发布
        }
        handleCancel();
      })
      return
  };

  // 查看详情
  const handleToSoaDetail = (record: abilityItem) => {
    setDetailInfo({ id: record.skillVersionId, skillName: record.skillName });
    setShowDetail(true);
  };

  // 状态记录表头
  const statusColumns: anyObj[] = [
    {
      title: '更新人员',
      dataIndex: 'importUserName',
      key: 'importUserName',
      width: '200px',
    },
    {
      title: '更新时间',
      dataIndex: 'importAt',
      key: 'importAt',
      width: '200px',
      render: (text: any) => {
        return text ? dayjs(text).format('YYYY-MM-DD HH:mm') : '';
      },
    },
    {
      title: '品牌',
      key: 'brand',
      dataIndex: 'brand',
      width: '200px',
    },
    {
      title: '车系',
      key: 'seriesCode',
      dataIndex: 'seriesCode',
      width: '200px',
      render: (_: any, item: any) => {
        let seriesName = '';
        if (carMap) {
          seriesName = carMap[item.seriesCode]?.seriesName || '';
        }
        return <span>{seriesName}</span>;
      },
    },
    {
      title: '车型',
      key: 'modelCode',
      dataIndex: 'modelCode',
      width: '200px',
      render: (_: any, item: any) => {
        let modelName = '';
        if (carMap) {
          modelName = carMap[item.seriesCode]?.models[item.modelCode]?.modelName || '';
        }
        return <span>{modelName}</span>;
      },
    },
    {
      title: '服务矩阵版本号',
      dataIndex: 'socVersion',
      key: 'socVersion',
    },
    {
      title: '最新状态',
      dataIndex: 'status',
      key: 'status',
      render: (_: any, record: any) => {
        if (record.status === 0) {
          return <span style={{ color: 'rgba(0,0,0,0.85)' }}>待发布</span>;
        } else if (record.status === 1) {
          return <span style={{ color: '#00a870' }}>已发布</span>;
        } else if (record.status === 2) {
          return <span style={{ color: '#ff7918' }}>已退回</span>;
        } else {
          return '';
        }
      },
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      width: '100px',
      fixed: 'right',
      render: (_: any, record: any) => (
        <Space size="middle">
          <Button type="link" onClick={() => handleStatusDetail(record)}>
            查看
          </Button>
        </Space>
      ),
    },
  ];

  const iconTextStyle = {
    color: '#fff',
    display: 'inline-block',
    fontSize: '12px',
    borderRadius: '5px',
  };

  // 能力表头
  const columns: anyObj[] = [
    {
      title: '',
      key: 'icon',
      dataIndex: 'icon',
      align: 'right',
      width: '40px',
      render: (_: any, item: any) => {
        return (
          <div style={{ display: 'flex', alignItems: 'center' }}>
            {/* 未发布能力才有差分标记 */}
            {
              activeKey === 2 && <>
              {item.isNew && (
                <>
                  <div
                    className={styles.commonIcon}
                    style={{
                      ...iconTextStyle,
                      backgroundColor: renderIcon('isNew')?.style?.color,
                    }}
                  >
                    {renderIcon('isNew')?.text}
                  </div>
                </>
              )}
              {item.isChange && (
                <>
                  <div
                    className={styles.commonIcon}
                    style={{
                      ...iconTextStyle,
                      backgroundColor: renderIcon('isChange')?.style?.color,
                    }}
                  >
                    {renderIcon('isChange')?.text}
                  </div>
                </>
              )}
              {item.isDelete && (
                <>
                  <div
                    className={styles.commonIcon}
                    style={{
                      ...iconTextStyle,
                      backgroundColor: renderIcon('isDelete')?.style?.color,
                    }}
                  >
                    {renderIcon('isDelete')?.text}
                  </div>
                </>
              )}
              </>
            }
          </div>
        );
      },
    },
    {
      title: '能力名称',
      width: '200px',
      key: 'skillName',
      dataIndex: 'skillName',
    },
    {
      title: '能力ID',
      dataIndex: 'skillId',
      key: 'skillId',
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
    },
    {
      title: '能力类型',
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: '品牌',
      key: 'brand',
      dataIndex: 'brand',
      width: '200px',
    },
    // {
    //   title: '车系',
    //   key: 'seriesCode',
    //   dataIndex: 'seriesCode',
    //   width: '200px',
    //   render: (_: any, item: any) => {
    //     let seriesName = '';
    //     if (carMap) {
    //       seriesName = carMap[item.seriesCode]?.seriesName || '';
    //     }
    //     return <span>{seriesName}</span>;
    //   },
    // },
    // {
    //   title: '车辆型号',
    //   key: 'modelCode',
    //   dataIndex: 'modelCode',
    //   render: (_: any, item: any) => {
    //     let seriesName = '',
    //       modelName = '';
    //     if (carMap) {
    //       seriesName = carMap[item.seriesCode]?.seriesName || '';
    //       modelName = carMap[item.seriesCode]?.models[item.modelCode]?.modelName || '';
    //     }
    //     return <span>{`${seriesName}/${modelName}`}</span>;
    //   },
    // },
    {
      title: '车系',
      dataIndex: 'seriesCode',
      key: 'seriesCode',
      width: '100px',
      render: (sCode: string) => {
          return <span>{carMap[sCode]?.seriesName || ''}</span>;
      },
    },
    {
        title: '车型',
        dataIndex: 'modelCode',
        key: 'modelCode',
        render: (modelCode: string, item: any) => {
            return <span>{carMap[item?.seriesCode]?.models[modelCode]?.modelName || ''}</span>;
        },
    },
    {
      title: '导入人员帐号',
      dataIndex: 'handleUserName',
      key: 'handleUserName',
    },
    {
      title: '导入时间',
      dataIndex: 'handleTime',
      key: 'handleTime',
      render: (text: any) => {
        return text ? dayjs(text).format('YYYY-MM-DD HH:mm') : '';
      },
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      width: '100px',
      fixed: 'right',
      render: (_: any, record: any) => {
        if (!record.isDelete) {
          return (
        <Space size="middle">

            <Button type="link" onClick={() => handleToSoaDetail(record)}>
              查看
            </Button>
            </Space>
          );
        } else {
          return null;
        }
      },
    },
  ];

  const expandedRowRender = (record: any) => {
    const columns: TableColumnsType<ExpandedDataType> = [
      {
        title: '',
        dataIndex: 'isNew',
        key: 'isNew',
        align: 'right',
        width: '40px',
        render: () => '',
      },
      {
        title: '操作人员',
        dataIndex: 'operator',
        key: 'operator',
        width: '200px',
      },
      {
        title: '操作时间',
        dataIndex: 'operationAt',
        key: 'operationAt',
        width: '200px',
        render: (text: any) => {
          return text ? dayjs(text).format('YYYY-MM-DD HH:mm') : '';
        },
      },
      {
        title: '操作记录',
        dataIndex: 'operationType',
        key: 'operationType',
        width: '200px',
        render: (text: number) => {
          if (text === 4) {
            return <span>退回</span>;
          } else {
            return '';
          }
        },
      },
      {
        title: '备注',
        dataIndex: 'reason',
        key: 'reason',
        render: (text: string | null) => {
          return (
            <Tooltip placement="top" title={text}>
              {' '}
              <div
                style={{
                  width: '400px',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                }}
              >
                {text}
              </div>
            </Tooltip>
          );
        },
      },
    ];
    if (record.backDetail) {
      return (
        <Table
          pagination={false}
          columns={columns}
          rowKey={'hisId'}
          scroll={{ x: 'max-content' }}
          dataSource={[record.backDetail]}
        />
      );
    } else {
      return null;
    }
  };

  // 导出能力
  const handleExportAblity = () => {
    showConfirm(
      {
        actionType: 'export',
        content: (
          <Row>
            <Col span={24}>
              将下载{seriesName || ''}/{modelName}车型{socVersion}
              版本的能力，请确认是否下载？
            </Col>
          </Row>
        )
      }
    );
  };

  // 导出模板
  const handleExportTemplate = () => {
    downloadAbilityFile();
  };

  const menus = (
    <Menu>
      {abilityList.length > 0 && socVersion && (
        <Menu.Item key={1} onClick={handleExportAblity}>
          导出能力
        </Menu.Item>
      )}
      <Menu.Item key={2} onClick={handleExportTemplate}>
        导出模板
      </Menu.Item>
    </Menu>
  );

  const handleTableChange = (pn: TablePaginationConfig) => {
    if (activeKey == 1) {
      getStatusLists(pn.current, pn.pageSize);
    } else {
      getList(pn.current, pn.pageSize, cartypeVal, socVersion, activeKey == 2 ? 0 : 1);
    }
  };

  // 查看状态记录详情
  const handleStatusDetail = (record: any) => {
    // 需要把搜索条件带到能力列表，并且使用当前值作为查询条件
    if (record.status === 0 || record.status === 2) {
      setActiveKey(2);
      setStatus(0);
    } else if (record.status == 1) {
      setActiveKey(3);
      setStatus(1);
      setLoading(true);
      // 状态记录跳转到已发布页面需要查询soc列表
      getPublishedSocList(false, record.seriesCode, record.modelCode);
    }
    setStatusDetail(true);
    setSocVersion(record.socVersion);
    setCartypeVal([record.seriesCode, record.modelCode]);
  };
  useEffect(() => {
    if (abilityList && abilityList.length) {
      setAbilityList([]);
    }
    if (status && socVersion) {
      setSocVersion('');
    }
    getCarType();
    if (status == -1) {
      getStatusLists(1, 10);
      dispatch({
        type: 'vehicleInfoQuery/getData',
        payload: {
          url: '/common/vehicle/getcurrentbrand',
        },
        callback: (e: any) => {
          if (e?.data?.[0]?.brandName) {
            setBrandName(e?.data?.[0]?.brandName)
          }
        },
      })
    }
  }, [status]);

  const handleGetSearchDisabeled = useCallback(()=> {
    // fix: 车型 和 服务矩阵版本号 才不禁用按钮 其余情况都禁用
    if (socVersion && cartypeVal.length === 2) {
      return false;
    }
    return true;
}, [socVersion, cartypeVal]);

  const handleCancel = () => {
    setIsModalBack(false);
    form.resetFields();
  }

  return (
    <div className={styles.abilityContainer}>
      <CustomSpin spinning={loading}>
        <PageTabs
          activeKey={activeKey}
          tabPaneList={tabPaneList}
          setActiveKey={handleTabChange}
          unpublishTotal={unpublishTotal}
        />
        {activeKey != 1 && (
          <Form form={form} name="control-hooks" className="abilityForm">
            <div className={styles.container}>
              <Row className={styles.row}>
                <div style={{ margin: '20px 20px 0 0' }}>
                  {activeKey !== 1 ? (
                    <div style={{ display: 'flex' }}>
                      <Col style={{ marginRight: '20px', }} span={5}>
                        <Input
                          value={skillName}
                          maxLength={20}
                          placeholder="请输入能力名称进行筛选"
                          style={{ maxWidth: '240px' }}
                          onPressEnter={() => getList(1, pagination.pageSize, cartypeVal, socVersion, status)}
                          onChange={(e) => setSkillName(e.target.value)}
                          suffix={
                            <SearchOutlined
                              onClick={() => getList(1, pagination.pageSize, cartypeVal, socVersion, status)}
                              style={{ color: 'rgba(0,0,0,.45)' }}
                            />
                          }
                        />
                      </Col>
                      <Col style={{ marginRight: '20px', display: 'flex', flexWrap: 'nowrap', height: 32, whiteSpace: 'nowrap' }} span={5}>
                        <span style={{ display: 'inline-block', lineHeight: '32px', width: 42 }}>
                          品牌：
                        </span>
                        <span style={{ display: 'none' }}>{brandName}</span>
                        <Input
                          disabled
                          value={brandName}
                          placeholder="请输入品牌"
                          style={{ height: 32 }}
                        />
                      </Col>
                      <Col style={{ marginRight: '20px', display: 'flex', flexWrap: 'nowrap', height: 32, whiteSpace: 'nowrap' }} span={6}>
                        <span style={{ display: 'inline-block', lineHeight: '32px', width: 42 }}>
                          车型：
                        </span>
                        <CarModelTreeSelect
                          carModelList={cartype}
                          othProps={{
                            allowClear: false,
                            size: 'large',
                            style: {
                              display: 'inline-block',
                              width: 'calc(100% - 42px)'
                            },
                          }}
                          allOptionNum={!status}
                          allOptionDot={!status}
                          carVal={cartypeVal}
                          emitSelect={(e: any) => emitSelect(e)}
                        />
                      </Col>
                      <Col style={{ display: 'flex', flexWrap: 'nowrap' }} span={7}>
                        <span style={{ display: 'inline-block', lineHeight: '32px', width: 115, height: 32, whiteSpace: 'nowrap' }}>
                          服务矩阵版本号：
                        </span>
                        <Select
                          value={socVersion}
                          disabled={status == 0}
                          onChange={(value) => {
                            setSocVersion(value);
                            // const newVal = carModalCopy;
                            // newVal[2] = value;
                            // setCartypeVal([newVal[0], newVal[1]])
                            // setcarModalCopy(newVal);
                          }}
                          placeholder="请选择"
                        >
                          {socVersions.map((item) => (
                            <Option value={item} key={item}>
                              {item}
                            </Option>
                          ))}
                        </Select>
                      </Col>
                    </div>
                  ) : null}
                </div>
                <div style={{ display: 'flex', justifyContent: 'flex-end', flexGrow: 1 }}>
                  {activeKey !== 1 && (
                    <div style={{ padding: '25px 0' }}>
                      {activeKey === 2 ? (
                        <div>
                          <div>
                            <Button
                              type="primary"
                              size={'small'}
                              style={{ margin: activeKey == 2 ? '0 8px 8px 0' : '0 8px 0 0' }}
                              disabled={handleGetSearchDisabeled()}
                              onClick={() => getList(1, pagination.pageSize, cartypeVal, socVersion, status)}
                            >
                              查询
                            </Button>
                            {hasAuth.import && <Button
                              type="primary"
                              size={'small'}
                              style={{ margin: '0 8px 8px 0' }}
                              onClick={() => {
                                setIsModalVisible(true);
                                setFileList([]);
                                setCarSeries([]);
                                setCarModels([]);
                                setImportCarModeVersion('');
                              }}
                            >
                              导入
                            </Button>}
                            {hasAuth.unpublishexport && <Dropdown overlay={menus}>
                              <Button type={'primary'} size={'small'}>
                                <Space>导出</Space>
                                <DownOutlined />
                              </Button>
                            </Dropdown>
                            }
                          </div>
                          <div>
                            {hasAuth.back && <Button
                              size={'small'}
                              style={{ marginRight: '8px' }}
                              disabled={!(!isBack && socVersion)}
                              onClick={() => {
                                setIsModalBack(true);
                                setModelOptions({
                                  title: <TextTitle text='退回' />,
                                  handleOk: handleBackOk,
                                  content: (
                                    <CarModel form={form} seriesModelList={seriesModelList} >
                                      <Form.Item
                                          label="请填写"
                                          name="reason"
                                          rules={[
                                            { required: true, message: '请填写退回原因!' },
                                            { pattern: /^.{5,}$/, message: '请至少输入5个字符!' },
                                          ]}
                                      >
                                          <Input.TextArea className={styles.reason} rows={4} maxLength={200} placeholder="请输入最少五个字符"  />
                                      </Form.Item>
                                    </CarModel>
                                  )
                                })
                              }}
                            >
                              退回
                            </Button>}
                            {hasAuth.publish && <Button
                              size={'small'}
                              style={{ marginRight: '8px' }}
                              disabled={!(cartypeVal.length && socVersion)}
                              onClick={() => getChangeList()}
                            >
                              发布
                            </Button>}
                            {hasAuth.cleanUp && <Button
                              size={'small'}
                              disabled={!(cartypeVal.length && socVersion)}
                              onClick={() => handleCleanUp()}
                            >
                              清空
                            </Button>}
                          </div>
                        </div>
                      ) : (
                        <div>
                          <Button
                            type="primary"
                            size={'small'}
                            style={{ margin: activeKey == 2 ? '0 8px 8px 0' : '0 8px 0 0' }}
                            disabled={handleGetSearchDisabeled()}
                            onClick={() => getList(1, pagination.pageSize, cartypeVal, socVersion, status)}
                          >
                            查询
                          </Button>
                          {hasAuth.publishexport && <Button
                            type="primary"
                            size={'small'}
                            style={{ marginRight: '8px' }}
                            disabled={!(cartypeVal.length && socVersion && abilityList.length)}
                            onClick={() => handleExportAblity()}
                          >
                            导出
                          </Button>}
                          {hasAuth.takeDown && <Button
                            size={'small'}
                            disabled={!(cartypeVal.length && socVersion)}
                            onClick={() => handleTakeDown()}
                          >
                            下架
                          </Button>}
                        </div>
                      )}
                    </div>
                  )}
                </div>
              </Row>
            </div>
          </Form >
        )}
        <Card bordered={false} style={{ marginTop: 10 }}>
          <div className={styles.tableContainer}>
            <ConfigProvider renderEmpty={() => emptyText(status, '能力')}>
              {activeKey === 1 ? (
                <Table
                  showHeader={abilityList.length > 0}
                  scroll={{ x: 'max-content' }}
                  columns={activeKey == 1 ? statusColumns : columns}
                  rowKey={(record) => {
                    if (activeKey == 1 && record.socId) {
                      return record.socId;
                    } else {
                      return record.skillVersionId;
                    }
                  }}
                  dataSource={abilityList}
                  onChange={handleTableChange}
                  rowClassName={(record: any) => renderRowClassName(record)}
                  pagination={{
                    size: 'small',
                    ...pagination,
                    showSizeChanger: true,
                    showQuickJumper: true,
                    position: ['bottomRight'],
                    showTotal,
                  }}
                  expandable={{
                    expandIcon: ({ expanded, onExpand, record }) => {
                      if (record.backDetail) {
                        if (expanded) {
                          return <UpOutlined onClick={(e) => onExpand(record, e)} />;
                        } else {
                          return <DownOutlined onClick={(e) => onExpand(record, e)} />;
                        }
                      } else {
                        return null;
                      }
                    },
                    expandedRowRender,
                  }}
                />
              ) : (
                <Table
                  showHeader={abilityList.length > 0}
                  columns={columns}
                  rowKey="skillVersionId"
                  dataSource={abilityList}
                  scroll={{ x: 'max-content' }}
                  onChange={handleTableChange}
                  rowClassName={(record: any) => {
                    {/* 未发布能力才有差分标记 */}
                    if (activeKey === 2) {
                      return renderRowClassName(record);
                    }
                    return 'row-header-default';
                  }}
                  pagination={{
                    size: 'small',
                    ...pagination,
                    showSizeChanger: true,
                    showQuickJumper: true,
                    position: ['bottomRight'],
                    showTotal,
                  }}
                />
              )}
            </ConfigProvider>
          </div>
        </Card>
        <DrawerAbilityDetail
          query={detailInfo}
          setShowDetail={setShowDetail}
          showDetail={showDetail}
        />
        {/* 导入弹窗 */}
        <ModalWin
          width={580}
          title="请选择车系车型和服务矩阵版本号"
          destroyOnClose
          keyboard={false}
          visible={isModalVisible}
          wrapClassName={styles.importModal}
          confirmLoading={importBtnLoading}
          onCancel={() => handleImportCancel()}
          footer={[
            <Button type="default" size={'small'} key="1" onClick={() => handleImportCancel()}>
              取消
            </Button>,
            <Button type="primary" size={'small'} key="2" onClick={() => handleImportOk({
              carModels,
              carSeries,
            }, false)}>
              导入
            </Button>,
          ]}
        >
          <Row className={styles.commonRow}>
            <div className={styles.commonLabel}>
              <span style={{ color: '#ff4d4f', marginRight: '4px' }}>*</span>
              <span>车系：</span>
            </div>
            <div className={styles.commonItem}>
              <Select placeholder={'请选择车系'} style={{ width: "100%" }} value={carSeries} onChange={handleProvinceChange}>
                {seriesModelList?.data?.data?.map?.((obj: any) => (
                  <Option value={obj.code} key={obj.code}>
                    {obj.name}
                  </Option>
                ))}
              </Select>
            </div>
          </Row>
          <Row style={{ marginTop: 20 }}>
            <div className={styles.commonLabel}>
              <span style={{ color: '#ff4d4f', marginRight: '4px' }}>*</span>
              <span>服务矩阵版本号：</span>
            </div>
            <div className={styles.commonItem}>
              <Select
                showSearch
                disabled={status == 1}
                value={importCarModeVersion}
                placeholder="请选择"
                onChange={handleSocVersionChange}
                style={{ width: '100%' }}
              >
                {publishList.map((item, index) => {
                  return (
                    <Option key={index} value={item.socVersion}>
                      {item.socVersion}
                    </Option>
                  );
                })}
              </Select>
            </div>
          </Row>
          <Row style={{ marginTop: 20 }} className={styles.commonRow}>
            <div className={styles.commonLabel}>
              <span style={{ color: '#ff4d4f', marginRight: '4px' }}>*</span>
              <span>车型：</span>
            </div>
            <div className={styles.commonItem}>
              <Select
                mode="multiple"
                showArrow
                placeholder={'请选择车型'}
                style={{ width: "100%" }} value={carModels} onChange={handleCarModelOnchange}
                dropdownRender={(menu) => (
                  <>
                    {menu}
                    <Divider style={{ margin: '8px 0' }} />
                    <div className={styles.extraBtn}>
                      <div className={styles.extraBtnItem} onClick={allSelected}>
                        全部选择
                      </div>
                      <div className={styles.extraBtnItem} onClick={clearAll}>
                        全部取消
                      </div>
                    </div>
                  </>
                )}
              >
                {carModelList.map?.((obj: any) => (
                  <Option value={obj.code} key={obj.code}>
                    {obj.name}
                  </Option>
                ))}
              </Select>
            </div>
          </Row>
          <Row style={{ marginTop: 20 }}>
            <div className={styles.commonLabel}>
              <span style={{ color: '#ff4d4f', marginRight: '4px' }}>*</span>
              <span>选择文件：</span>
            </div>
            <div className={styles.commonItem}>
              <Upload
                {...propsForUpload}
                accept=".xls,.xlsx"
                maxCount={1}
                style={{ width: '100%' }}
              >
                <Input
                  // size="large"
                  style={{ width: '320px', marginRight: '12px' }}
                  value={fileList.length > 0 ? fileList[fileList.length - 1].name : ''}
                />
                <Button type="link" size="small">
                  选择
                </Button>
              </Upload>
            </div>
          </Row>
        </ModalWin>
        {/* 发布，导出,下架弹窗 */}
        {
          currentModal && (
            <ModalWin
              width="580px"
              keyboard={false}
              wrapClassName={styles.importModal}
              visible={currentModal.visible}
              title={renderModalTitle(currentModal.actionType)}
              onOk={() => renderAction(currentModal.actionType)}
              confirmLoading={currentModal.actionType === 'export' ? exportFileLoading : false}
              key={currentModal.actionType}
              onCancel={() => handleModalCancel(currentModal)}
              footer={[
                <Button
                  type="default"
                  key="1"
                  style={{ marginRight: '20px' }}
                  onClick={() => handleModalCancel(currentModal)}
                >
                  取消
                </Button>,
                <Button type="primary" key="2" onClick={() => renderAction(currentModal.actionType)}>
                  确定
                </Button>,
              ]}
            >
              {currentModal.content}
            </ModalWin>
          )
        }
        {/* 退回 */}
        <ModalWin
          title={modelOptions.title}
          wrapClassName={styles.backModal}
          keyboard={false}
          onOk={modelOptions.handleOk}
          visible={isModalBack}
          width="580px"
          onCancel={handleCancel}
          footer={[
            <Button type="default" key="1" onClick={handleCancel}>
              取消
            </Button>,
            <Button type="primary" key="2" onClick={modelOptions.handleOk}>
              确定
            </Button>,
          ]}
        >
          {
            modelOptions.content
          }
        </ModalWin>
      </CustomSpin >
      {/* 全局任务组件 */}
      <RequestSequence />
    </div >
  );
};

export default connect(({ abilityModel, menu, loading }: { abilityModel: any; menu: any; loading: any }) => ({
  abilityModel,
  menu,
  loading: loading.models.abilityModel,
}))(Index);
